﻿namespace Silverlight.Windows
{
    using System;
    using System.Windows;

    public enum StartupLocation { Manual, CenterOwner }

    public static class ModalWindowExtensions
    {
        /// <summary>
        /// ShowDialog shows the window and disables all other windows in the application.
        /// </summary>
        /// <param name="modalWindow"></param>
        /// <param name="ownerWindow">Optional owner window</param>
        /// <param name="startupLocation">Optional startup location</param>
        /// <param name="showInTaskBar">Optional task bar visibility</param>
        public static void ShowDialog(
            this Window modalWindow,
            Window ownerWindow = null,
            StartupLocation startupLocation = StartupLocation.Manual,
            bool showInTaskBar = false)
        {
            if (modalWindow == null) throw new ArgumentNullException("modalWindow");
            if (modalWindow == ownerWindow) throw new InvalidOperationException("Owner cannot be itself");
            if (startupLocation == StartupLocation.CenterOwner && ownerWindow == null)
                throw new InvalidOperationException("startupLocation cannot be CenterOwner if ownerWindow is null");

            Action<bool> enableOtherWindows = enable =>
                {
                    foreach (Window window in Application.Current.Windows)
                    {
                        if (window != modalWindow)
                        {
                            var hwnd = Hwnd.FindHwnd(window);
                            Hwnd.EnableWindow(hwnd, enable);
                        }
                    }
                };

            Action onOpen = () => enableOtherWindows(false);
            Action onClose = () => enableOtherWindows(true);

            ModalWindow.Show(onOpen, onClose, modalWindow, ownerWindow, startupLocation, showInTaskBar);
        }
    }
}

